/*
 * @lc app=leetcode.cn id=817 lang=cpp
 *
 * [817] 链表组件
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    int numComponents(ListNode *head, vector<int> &nums) {
        unordered_set<int> numsSet;
        for (int num : nums) {
            numsSet.emplace(num);
        }

        int isHead = 0, ans = 0;
        while (head) {
            if (numsSet.find(head->val) != numsSet.end()) {
                if (!isHead) {
                    isHead = 1;
                    ans++;
                }
            } else {
                isHead = 0;
            }
            head = head->next;
        }

        return ans;
    }
};
// @lc code=end
